#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
using namespace std;
Log lg;

void Usage(const string &proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cerr << "socket error" << endl;
            return 1;
        }
        //  客户端发起connect的时候，进行自动随机bind
        int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            lg(Fatal, "Client connect is error %s", strerror(errno));
            return 1;
        }

        while (true)
        {
            string message;
            cout << "Please Enter# ";
            getline(cin, message);

            int n = write(sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                cerr << "write error..." << endl;
                break;
            }
            else if (n == 0) {
                break;
            }

            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0)
            {
                inbuffer[n] = 0;
                cout << inbuffer << endl;
            }
            else if(n == 0) {
                break;
            }
        }
        close(sockfd);
    }

    return 0;
}